package com.ea.eadp.nexus.test.common;

import java.net.InetSocketAddress;
import java.util.EnumMap;
import java.util.List;

import net.spy.memcached.MemcachedClient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;

import com.ea.eadp.nexus.test.common.ApiClients.NexusConnectApi;
import com.ea.eadp.nexus.test.common.ApiClients.NexusGatewayApi;
import com.ea.eadp.nexus.test.common.ApiClients.NucleusApi;
import com.ea.eadp.nexus.test.pageDefinition.Signin_Web;
import com.ea.eadp.nexus.test.pageDefinition.newconsole.ContactPreferencesPage;
import com.ea.eadp.nexus.test.pageDefinition.newconsole.CreateOriginAccountPage;
import com.ea.eadp.nexus.test.pageDefinition.newconsole.OriginAccountPage;
import com.ea.eadp.nexus.test.pageDefinition.newconsole.SecurityQuestionPage;
import com.ea.eadp.nexus.test.pageDefinition.newconsole.WelcomeBackPage;
import com.ea.eadp.nexus.test.pageDefinition.newconsole.WelcomePage;
import com.ea.eadp.rest.identity.generated.PSNAccessTokenType;
import com.ea.eadp.test.shared.client.qahandlers.QaHandlersClient;
import com.ea.eadp.test.shared.utility.RandomFactory;
import com.ea.nucleus.qahandlers.sony.AuthorizationHeader;

/**
 * Created by YimingCao on 3/31/2015.
 */
public class SwitchableClientIdTestHelper {
    protected final Log log = LogFactory.getLog(getClass());
    private MemcachedClient memcachedClient;
    private QaHandlersClient qaHandlersClient;

    public static String SonyClientID1 = "33f3a6af-0a39-4c98-9870-bee66f2cbc57";
    public static String SonyClientSecret1 = "FRlEMIatH7uprl48";
    public static String SonyClientID2 = "9309b12a-3178-4839-bb00-ce5c8a128dfd";
    public static String SonyClientSecret2 = "FtkQH157C3cGt19N";

    public SwitchableClientIdTestHelper()
    {
        try {
            memcachedClient = new MemcachedClient(new InetSocketAddress(SystemProperties.instance().getProperty("test.onebox.host"), 11211));
        } catch (Exception ex) {
            Assert.fail("cannot start memcached client");
        }

        qaHandlersClient = new QaHandlersClient();
    }

    public void shutdownMemcacheClient()
    {
        memcachedClient.shutdown();
    }

    public enum TestAppClient
    {
        TWOPSNIDVERSION("MADDEN-16-PS4-CLIENT", "MADDEN-16-PS4-SERVER", "secret1", "secret1"),
        DEFAULTPSNIDVERSION("DAI-PS4-CLIENT", "DAI-PS4-BLAZE-SERVER", "2xPrGdz45FhtA77g29CIeziOw6I1FiJBbsCp53FXyLwrKaE0BrghnFzjtADszozhQscUVlBFmikHmOnTInNCkM5ocF6I2nh2UYXL", "MQCFFT7rn70xXNkl7lkprGRJjw6o23bcznPINzXh5pSmBB3G8OaBz1RAqI9HHvVAlSjSe0AAWsYUE4Cq2BQh9r35WOkcBWUINhYU");

        private String clientClientId;
        private String serverClientId;
        private String clientClientSecret;
        private String serverClientSecret;

        public String getClientClientId() {
            return clientClientId;
        }

        public void setClientClientId(String clientClientId) {
            this.clientClientId = clientClientId;
        }

        public String getServerClientId() {
            return serverClientId;
        }

        public void setServerClientId(String serverClientId) {
            this.serverClientId = serverClientId;
        }

        public String getClientClientSecret() {
            return clientClientSecret;
        }

        public void setClientClientSecret(String clientClientSecret) {
            this.clientClientSecret = clientClientSecret;
        }

        public String getServerClientSecret() {
            return serverClientSecret;
        }

        public void setServerClientSecret(String serverClientSecret) {
            this.serverClientSecret = serverClientSecret;
        }

        TestAppClient(String clientClientId, String serverClientId, String clientClientSecret, String serverClientSecret) {
            this.clientClientId = clientClientId;
            this.serverClientId = serverClientId;
            this.clientClientSecret = clientClientSecret;
            this.serverClientSecret = serverClientSecret;
        }
    }

    public enum AccessTokenProperty {
        CLIENTACCESSTOKEN,
        ACCESSTOKEN,
        EMAIL,
        PASSWORD,
        PS4TICKET,
        PERSONAID
    }

    public EnumMap<AccessTokenProperty, Object> getAccessToken(TestAppClient testAppClient) throws Exception
    {
        String ps4ticket;
        ps4ticket = RandomFactory.getRandomStringOfAlphabetOrNumeric(20);
        EnumMap<AccessTokenProperty, Object> result = getAccessToken(testAppClient, ps4ticket);
        result.put(AccessTokenProperty.PS4TICKET, ps4ticket);
        return result;
    }

    public EnumMap<AccessTokenProperty, Object> getAccessToken(TestAppClient testAppClient, String ticket) throws Exception
    {
        String signupPassword = "1qaz@WSX";
        String signupEmail = TestUtil.getRandomEmail();
        String pidUrl = NucleusApi.instance().postPid(signupEmail, signupPassword);
        Long pidID = TestUtil.getPidID(pidUrl);
        String originId = TestUtil.getRandomOriginId();
        String personaId = TestUtil.getPersonaID(NucleusApi.instance().postPersona(pidID, originId)).toString();
        NucleusApi.instance().postSecurityQA(pidID);

        EnumMap<AccessTokenProperty, Object> mid_result = getAccessToken(signupEmail, signupPassword, testAppClient, ticket);
        mid_result.put(AccessTokenProperty.EMAIL, signupEmail);
        mid_result.put(AccessTokenProperty.PASSWORD, signupPassword);
        return mid_result;
    }

    public EnumMap<AccessTokenProperty, Object> getAccessTokenByAutoLogin(TestAppClient testAppClient, String ticket) throws Exception {
        WebDriver webDriver = BrowserFactory.createChromeWebDriver();
        try {
            WelcomePage welcomePage = new WelcomePage(webDriver);
            welcomePage.navigate(TestUtil.getPS4ConnectUrl(testAppClient.getClientClientId(), null, "en", ticket));
            for (int i=0;i<5;i++){
                String url = TestUtil.getCurrentUrl(webDriver);
                if (url.contains("?code=")){
                    break;
                }
                Thread.sleep(1000);
            }
            String url = TestUtil.getCurrentUrl(webDriver);
            TestUtil.validatePageRedirection(webDriver);
            String code = url.substring(url.indexOf("?code=") + "?code=".length(), url.length());

            AccessToken userToken = NexusConnectApi.instance().getTokenByCodeWithClientSecret(code, testAppClient.getClientClientId(), testAppClient.getClientClientSecret());
            String serverCode = NexusConnectApi.instance().getCodeByToken(userToken, testAppClient.getServerClientId());
            AccessToken token = NexusConnectApi.instance().getTokenByCodeWithClientSecret(serverCode, testAppClient.getServerClientId(), testAppClient.getServerClientSecret());

            EnumMap<AccessTokenProperty, Object> retMap = new EnumMap<AccessTokenProperty, Object>(AccessTokenProperty.class);
            retMap.put(AccessTokenProperty.CLIENTACCESSTOKEN, userToken);
            retMap.put(AccessTokenProperty.ACCESSTOKEN, token);
            return retMap;
        } finally {
            webDriver.close();
            webDriver.quit();
        }
    }

    public EnumMap<AccessTokenProperty, Object> getAccessToken(String email, String password, TestAppClient testAppClient, String ticket) throws Exception{
        WebDriver webDriver = BrowserFactory.createChromeWebDriver();
        String code;

        try{
            WelcomePage welcomePage = new WelcomePage(webDriver);
            welcomePage.navigate(TestUtil.getPS4ConnectUrl(testAppClient.getClientClientId(), null, "en", ticket));
            welcomePage.waitPageLoadCompleted();
            welcomePage.acceptTOS();

            OriginAccountPage originAccountPage = new OriginAccountPage(webDriver);
            originAccountPage.waitPageLoadCompleted();
            originAccountPage.enterEmail(email);

            WelcomeBackPage welcomeBackPage = new WelcomeBackPage(webDriver);
            welcomeBackPage.waitPageLoadCompleted();
            welcomeBackPage.enterPassword(password);
            for (int i=0;i<5;i++){
                String url = TestUtil.getCurrentUrl(webDriver);
                if (url.contains("?code=")){
                    break;
                }
               Thread.sleep(1000);
            }
            String url = TestUtil.getCurrentUrl(webDriver);
            TestUtil.validatePageRedirection(webDriver);
            code = url.substring(url.indexOf("?code=") + "?code=".length(), url.length());
        } finally {
            webDriver.close();
            webDriver.quit();
        }

        AccessToken userToken = NexusConnectApi.instance().getTokenByCodeWithClientSecret(code, testAppClient.getClientClientId(), testAppClient.getClientClientSecret());
        String serverCode = NexusConnectApi.instance().getCodeByToken(userToken, testAppClient.getServerClientId());
        AccessToken token = NexusConnectApi.instance().getTokenByCodeWithClientSecret(serverCode, testAppClient.getServerClientId(), testAppClient.getServerClientSecret());

        EnumMap<AccessTokenProperty,Object> retMap = new EnumMap<AccessTokenProperty, Object>(AccessTokenProperty.class);
        retMap.put(AccessTokenProperty.CLIENTACCESSTOKEN, userToken);
        retMap.put(AccessTokenProperty.ACCESSTOKEN, token);
        return retMap;
    }

    public EnumMap<AccessTokenProperty, Object> getAccessTokenByRegister(TestAppClient testAppClient, StringBuffer ticket) throws Exception
    {
        if (ticket == null) ticket = new StringBuffer();
        ticket.delete(0, ticket.length());
        ticket.append(RandomFactory.getRandomStringOfAlphabetOrNumeric(20));
        return getAccessTokenByRegister(testAppClient, ticket.toString());
    }

    public EnumMap<AccessTokenProperty, Object> getAccessTokenByRegister(TestAppClient testAppClient, String ticket) throws Exception
    {
        WebDriver webDriver = BrowserFactory.createChromeWebDriver();
        String code;
        String personaId;
        try {
            String signupPassword = "1qaz@WSX";
            String signupEmail = TestUtil.getRandomEmail();

            WelcomePage welcomePage = new WelcomePage(webDriver);
            welcomePage.navigate(TestUtil.getPS4ConnectUrl(testAppClient.getClientClientId(), null, "en", ticket));
            welcomePage.waitPageLoadCompleted();
            welcomePage.acceptTOS();

            OriginAccountPage originAccountPage = new OriginAccountPage(webDriver);
            originAccountPage.waitPageLoadCompleted();
            String email = TestUtil.getRandomEmail();
            originAccountPage.enterEmail(email);

            CreateOriginAccountPage createOriginAccountPage = new CreateOriginAccountPage(webDriver);
            createOriginAccountPage.waitPageLoadCompleted();
            createOriginAccountPage.enterPassword(signupPassword);
            createOriginAccountPage.enterConfirmPassword(signupPassword);
            createOriginAccountPage.enterOriginId(TestUtil.getRandomOriginId());

            SecurityQuestionPage securityQuestionPage = new SecurityQuestionPage(webDriver);
            securityQuestionPage.waitPageLoadCompleted();
            securityQuestionPage.selectQuestion(2);
            securityQuestionPage.enterSecurityAnswer("aaaaaabbbbbb");

            ContactPreferencesPage contactPreferencesPage = new ContactPreferencesPage(webDriver);
            contactPreferencesPage.waitPageLoadCompleted();
            contactPreferencesPage.withoutSelectingShareInfo();
            for (int i=0;i<5;i++){
                String url = TestUtil.getCurrentUrl(webDriver);
                if (url.contains("?code=")){
                    break;
                }
                Thread.sleep(1000);
            }
            String url = TestUtil.getCurrentUrl(webDriver);
            TestUtil.validatePageRedirection(webDriver);
            code = url.substring(url.indexOf("?code=") + "?code=".length(), url.length());
        } finally {
            webDriver.close();
            webDriver.quit();

        }

        AccessToken userToken = NexusConnectApi.instance().getTokenByCodeWithClientSecret(code, testAppClient.getClientClientId(), testAppClient.getClientClientSecret());
        String serverCode = NexusConnectApi.instance().getCodeByToken(userToken, testAppClient.getServerClientId());
        AccessToken token = NexusConnectApi.instance().getTokenByCodeWithClientSecret(serverCode, testAppClient.getServerClientId(), testAppClient.getServerClientSecret());

        EnumMap<AccessTokenProperty,Object> retMap = new EnumMap<AccessTokenProperty, Object>(AccessTokenProperty.class);
        retMap.put(AccessTokenProperty.ACCESSTOKEN, token);
        return retMap;
    }

    public String getAccessTokenByTicket(String ticket, String index)
    {
        return "AT-" + ticket + "-" + index;
    }

    public String getTicketWithIndex(String ticket, String index)
    {
        return ticket + "-" + index;
    }

    public AccessToken getBattleLogAccessTokenByWebLogin(String email, String password) throws Exception
    {
        WebDriver webDriver = BrowserFactory.createChromeWebDriver();

        try {
            Signin_Web signin_web = new Signin_Web(webDriver);
            signin_web.navigate();
            signin_web.setSigninEmail(email);
            signin_web.setSigninPassword(password);
            signin_web.clickToSigninComplete();

            for (int i=0;i<5;i++){
                String url = TestUtil.getCurrentUrl(webDriver);
                if (url.contains("?code=")){
                    break;
                }
                Thread.sleep(1000);
            }
            String url = TestUtil.getCurrentUrl(webDriver);
            TestUtil.validatePageRedirection(webDriver);
            String code = url.substring(url.indexOf("?code=") + "?code=".length(), url.length());

            AccessToken accessToken = NexusConnectApi.instance().getTokenByUserPwdWithClientSecret(email, password, "battlelog", "battlelog_secret", null);

            return accessToken;
        } finally {
            webDriver.close();
            webDriver.quit();
        }
    }

    public AccessToken getBattleLogAccessToken(String ticket) throws Exception
    {
        WebDriver webDriver = BrowserFactory.createChromeWebDriver();
        String code;

        try {
            WelcomePage welcomePage = new WelcomePage(webDriver);
            welcomePage.navigate(TestUtil.getPS4ConnectUrl("battlelog", null, "en", ticket));
            for (int i=0;i<5;i++){
                String url = TestUtil.getCurrentUrl(webDriver);
                if (url.contains("?code=")){
                    break;
                }
                Thread.sleep(1000);
            }
            String url = TestUtil.getCurrentUrl(webDriver);
            TestUtil.validatePageRedirection(webDriver);
            code = url.substring(url.indexOf("?code=") + "?code=".length(), url.length());

            AccessToken accessToken = NexusConnectApi.instance().getTokenByCodeWithClientSecretAndRedirectUri(code, "battlelog", "battlelog_secret", null);
            return accessToken;
        } finally {
            webDriver.close();
            webDriver.quit();
        }
    }

    public enum SwitchableTestScenario{
        SCENARIO_RT_DEFAULT_AT_NEW(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE),
        SCENARIO_RT_DEFAULT_RT_NEW_AT_NEW(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE),
        SCENARIO_AT_NEW(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE),
        SCENARIO_RT_DEFAULT(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE),
        SCENARIO_RT_DEFAULT_AT_DEFAULT(Boolean.TRUE, Boolean.TRUE, Boolean.FALSE),
        SCENARIO_NONE(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE);

        public boolean isHas_refreshtoken_default() {
            return has_refreshtoken_default;
        }

        public boolean isHas_accesstoken_default() {
            return has_accesstoken_default;
        }

        public boolean isHas_accesstoken_new() {
            return has_accesstoken_new;
        }

        private final boolean has_refreshtoken_default;
        private final boolean has_accesstoken_default;
        private final boolean has_accesstoken_new;

        SwitchableTestScenario(boolean has_refreshtoken_default, boolean has_accesstoken_default, boolean has_accesstoken_new)
        {
            this.has_accesstoken_default = has_accesstoken_default;
            this.has_accesstoken_new = has_accesstoken_new;
            this.has_refreshtoken_default = has_refreshtoken_default;
        }
    }

    public enum SwitchableTestAgainst{
        Default_Version_Console,
        New_Version_Console,
        Battle_Log
    }

    public EnumMap<AccessTokenProperty, Object> preparation_simulate_ui(SwitchableTestScenario scenario, SwitchableTestAgainst against) throws Exception {
        if (against == SwitchableTestAgainst.Default_Version_Console && (scenario == SwitchableTestScenario.SCENARIO_AT_NEW || scenario == SwitchableTestScenario.SCENARIO_NONE))
            throw new Exception();

        String ps4_ticket = null;
        String email = null;
        String password = null;
        String personaId = null;

        AccessToken nexusAccessTokenForDefaultVersion = null;
        AccessToken nexusAccessTokenForNewVersion = null;

        if (scenario.has_refreshtoken_default) {
            log.info("scenario has default RT");
            EnumMap<AccessTokenProperty, Object> tempResult = this.getAccessToken(TestAppClient.DEFAULTPSNIDVERSION);
            nexusAccessTokenForDefaultVersion = (AccessToken) tempResult.get(AccessTokenProperty.ACCESSTOKEN);
            TokenInfo tokenInfo = NexusConnectApi.instance().getTokenInfo(nexusAccessTokenForDefaultVersion);
            personaId = tokenInfo.getPersona_id();
            ps4_ticket = (String) tempResult.get(AccessTokenProperty.PS4TICKET);
            email = (String) tempResult.get(AccessTokenProperty.EMAIL);
            password = (String) tempResult.get(AccessTokenProperty.PASSWORD);
        }

        if (scenario.has_accesstoken_default) {
            if (scenario.has_refreshtoken_default != true) throw new Exception();

            log.info("scenario has default AT");
            PSNAccessTokenType psnAccessToken = NexusGatewayApi.instance().getPsnAccessToken(nexusAccessTokenForDefaultVersion, personaId);
        }

        if (scenario.has_accesstoken_new) {
            log.info("scenario has new AT");
            if (ps4_ticket != null) {
                log.info("auto login");
                EnumMap<AccessTokenProperty, Object> tempResult = this.getAccessTokenByAutoLogin(TestAppClient.TWOPSNIDVERSION, ps4_ticket);
                nexusAccessTokenForNewVersion = (AccessToken) tempResult.get(AccessTokenProperty.ACCESSTOKEN);
            } else {
                log.info("login");
                EnumMap<AccessTokenProperty, Object> tempResult = this.getAccessToken(TestAppClient.TWOPSNIDVERSION);
                nexusAccessTokenForNewVersion = (AccessToken) tempResult.get(AccessTokenProperty.ACCESSTOKEN);
                TokenInfo tokenInfo = NexusConnectApi.instance().getTokenInfo(nexusAccessTokenForNewVersion);
                personaId = tokenInfo.getPersona_id();
                ps4_ticket = (String) tempResult.get(AccessTokenProperty.PS4TICKET);
                email = (String) tempResult.get(AccessTokenProperty.EMAIL);
                password = (String) tempResult.get(AccessTokenProperty.PASSWORD);
            }
        }

        EnumMap<AccessTokenProperty, Object> myResult = new EnumMap<AccessTokenProperty, Object>(new EnumMap<AccessTokenProperty, Object>(AccessTokenProperty.class));

        if (against == SwitchableTestAgainst.Default_Version_Console) {
            myResult.put(AccessTokenProperty.ACCESSTOKEN, nexusAccessTokenForDefaultVersion);
            log.info("caller AT = " + nexusAccessTokenForDefaultVersion.getAccess_token());
        } else if (against == SwitchableTestAgainst.New_Version_Console) {
            if (nexusAccessTokenForNewVersion != null)
                myResult.put(AccessTokenProperty.ACCESSTOKEN, nexusAccessTokenForNewVersion);
            else
            {
                if (ps4_ticket != null) {
                    log.info("auto login");
                    EnumMap<AccessTokenProperty, Object> tempResult = this.getAccessTokenByAutoLogin(TestAppClient.TWOPSNIDVERSION, ps4_ticket);
                    nexusAccessTokenForNewVersion = (AccessToken)tempResult.get(AccessTokenProperty.ACCESSTOKEN);
                } else {
                    log.info("login");
                    EnumMap<AccessTokenProperty, Object> tempResult = this.getAccessToken(TestAppClient.TWOPSNIDVERSION);
                    nexusAccessTokenForNewVersion = (AccessToken) tempResult.get(AccessTokenProperty.ACCESSTOKEN);
                    TokenInfo tokenInfo = NexusConnectApi.instance().getTokenInfo(nexusAccessTokenForNewVersion);
                    personaId = tokenInfo.getPersona_id();
                    ps4_ticket = (String) tempResult.get(AccessTokenProperty.PS4TICKET);
                    email = (String) tempResult.get(AccessTokenProperty.EMAIL);
                    password = (String) tempResult.get(AccessTokenProperty.PASSWORD);
                }
                myResult.put(AccessTokenProperty.ACCESSTOKEN, nexusAccessTokenForNewVersion);
                String cachedNewVersionPSNAccessToken = (String)memcachedClient.get(getPSNAccessTokenCacheKey(personaId, "INT", "2"));
                Assert.assertNotNull(cachedNewVersionPSNAccessToken);
                memcachedClient.delete(getPSNAccessTokenCacheKey(personaId, "INT", "2"));
            }
            log.info("caller AT = " + nexusAccessTokenForNewVersion.getAccess_token());
        } else if (against == SwitchableTestAgainst.Battle_Log) {
            if (email == null) {
                String _signupPassword = "1qaz@WSX";
                String _signupEmail = TestUtil.getRandomEmail();
                String _pidUrl = NucleusApi.instance().postPid(_signupEmail, _signupPassword);
                Long _pidID = TestUtil.getPidID(_pidUrl);
                String _originId = TestUtil.getRandomOriginId();
                personaId = TestUtil.getPersonaID(NucleusApi.instance().postPersona(_pidID, _originId)).toString();
                NucleusApi.instance().postSecurityQA(_pidID);
                email = _signupEmail;
                password = _signupPassword;
            }
            AccessToken accessTokenForBattleLog = getBattleLogAccessTokenByWebLogin(email, password);
            log.info("caller AT = " + accessTokenForBattleLog.getAccess_token());
            myResult.put(AccessTokenProperty.ACCESSTOKEN, accessTokenForBattleLog);
        }
        myResult.put(AccessTokenProperty.PS4TICKET, ps4_ticket);
        myResult.put(AccessTokenProperty.EMAIL, email);
        myResult.put(AccessTokenProperty.PASSWORD, password);
        myResult.put(AccessTokenProperty.PERSONAID, personaId);

        log.info("personaId = " + personaId);
        log.info("ps4_ticket = " + ps4_ticket);
        log.info("email = " + email);
        log.info("password = " + password);
        return myResult;
    }

    private String getPSNAccessTokenCacheKey(String personaId, String environment, String sonyClientIdVersion)
    {
        if (sonyClientIdVersion == null) {
            return String.format("%s%s_%s", "33:psn_accesstoken_2_", personaId, environment);
        } else {
            return String.format("%s%s_%s_%s", "33:psn_accesstoken_2_", personaId, environment, sonyClientIdVersion);
        }
    }

    public boolean ifHavingAccessTokenInCache(String personaId, String version)
    {
        String cachedNewVersionPSNAccessToken = (String)memcachedClient.get(getPSNAccessTokenCacheKey(personaId, "INT", version));
        return cachedNewVersionPSNAccessToken == null ? false : true;
    }

    public void deleteAccessTokenInCache(String personaId, String version)
    {
        memcachedClient.delete(getPSNAccessTokenCacheKey(personaId, "INT", version));
    }

    public void deleteAllHistoryForKeyFromSony(String key)
    {
        qaHandlersClient.deleteSonyAuthorizationHeader(null, key);
    }

    public String getLastPSNAccessTokenByClientId(String key, String sonyClientId, String sonyClientSecret)
        {
        String result = null;
        List<AuthorizationHeader> authorizationHeaderList = qaHandlersClient.getSonyAuthorizationHeader(null, key);
        for (AuthorizationHeader x : authorizationHeaderList)
        {
            if (x.getOutputAccessToken() != null)
            {
                if (sonyClientId.equals(x.getClientId()) && sonyClientSecret.equals(x.getClientSecret()))
                {
                    result = x.getOutputAccessToken();
                }
            }
        }
        log.info(result);
        return result;
    }

    public void verifyAllCallIsUsingClientId(String key, String lastAccessToken, String sonyClientID, String sonyClientSecret, int expectedCount)
    {
        String currentAccessToken = lastAccessToken;
        List<AuthorizationHeader> authorizationHeaderList = qaHandlersClient.getSonyAuthorizationHeader(null, key);

        Assert.assertEquals(authorizationHeaderList.size(), expectedCount);

        for (AuthorizationHeader x : authorizationHeaderList)
        {
            if (x.getOutputAccessToken() != null)
            {
                if (sonyClientID.equals(x.getClientId()) == false || sonyClientSecret.equals(x.getClientSecret()) == false)
                {
                    Assert.fail();
                }
                else currentAccessToken = x.getOutputAccessToken();
            }
            else
            {
                if (currentAccessToken.equals(x.getAccessToken()) == false)
                {
                    Assert.fail();
                }
            }
        }
    }
}
